package cn.gwm.flink.streaming.dwm.charge.util;

import cn.gwm.flink.streaming.client.RedisClient;
import cn.gwm.flink.streaming.constant.BaseFields;
import cn.gwm.utils.GpsBean;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.*;

/**
 * @ClassName LastGPSUtil
 * @Description 最后gps点位
 * @Author LiangGuang
 * @Date 2023/04/12 18:12
 */
public class LastGPSUtil {

    /**
     * redis中 关于最后经纬度的业务key
     */
    private static final String REDIS_LAST_GPS = "l_gps:";
    /**
     * 最后点位可信任 时长
     */
    private static final Integer LONG_TIME = 2;


    /**
     * redis中最后的点位
     *
     * @param vehicletype
     * @param vin
     * @param time
     * @return
     */
    public static GpsBean redisLastGPS(String vehicletype, String vin, Long time) {
        GpsBean bean = new GpsBean();
        String data = RedisClient.getData(REDIS_LAST_GPS + vehicletype + ":" + vin);
        if (data != null) {
            JSONObject entries = JSONUtil.parseObj(data);
            // 时间比较
            if (Math.abs(entries.getLong(BaseFields.tid) - time) < LONG_TIME * 60 * 1000L) {
                bean.setWgLat(entries.getDouble(BaseFields.LATITUDE));
                bean.setWgLon(entries.getDouble(BaseFields.LONGITUDE));
            }
        }
        return bean;
    }


    public static List<Object> filterInnerTime(String vehicletype, String vin, Long time) {
        Set<String> vinGpsSet = RedisClient.jedisCluster.hkeys(REDIS_LAST_GPS + vehicletype + ":" + vin);

        List<Object> list = vinGpsSet.stream()
                .filter(item -> Math.abs(Long.valueOf(item) - time) < LONG_TIME * 60 * 1000L)
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        return list;
    }

    public static List<List<String>> trustableRedisGPS(String vehicletype, String vin, List<Object> list) {

        List<List<String>> result = new ArrayList<>();

        Map<String, String> stringMap = RedisClient.jedisCluster.hgetAll(REDIS_LAST_GPS + vehicletype + ":" + vin);
        list.forEach(item -> {
            if (stringMap.containsKey(item)) {
                // 将 string 转为json
                JSONObject entries = JSONUtil.parseObj(stringMap.get(item));
                result.add(Arrays.asList(entries.getStr("latitude"), entries.getStr("longitude")));
            }
        });

        return result;
    }


}
